package top.houry.test;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import top.houry.grpc.proto.OpenAPIGrpc;
import top.houry.grpc.proto.TestGrpc;

public class BidirectionalStreamingClientGrpc {
    public static void main(String[] args) {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9999).usePlaintext().build();
        OpenAPIGrpc.OpenAPIStub newStub = OpenAPIGrpc.newStub(channel);
       // TestGrpc.Request request = TestGrpc.Request.newBuilder().setName("小猴子").build();
        StreamObserver<TestGrpc.Response> responseObserver = new StreamObserver<TestGrpc.Response>() {

            @Override
            public void onNext(TestGrpc.Response value) {
                System.out.println("Received response: " + value.getMessage());
            }

            @Override
            public void onError(Throwable t) {
                System.err.println("Error: " + t.getMessage());
            }

            @Override
            public void onCompleted() {
                System.out.println("Server completed.");
            }
        };

        StreamObserver<TestGrpc.Request> requestStreamObserver = newStub.bidirectionalStreaming(responseObserver);

        for (int i = 0; i < 5; i++) {
            TestGrpc.Request builder = TestGrpc.Request.newBuilder().setName("222222").build();
            requestStreamObserver.onNext(builder);
        }
        requestStreamObserver.onCompleted();
        // 等待完成
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        channel.shutdown();
    }
}
